<?php

/**
 * User
 *
 * PHP version 5
 *
 * @category Model
 * @package  MIAOCMS
 * @version  1.0
 */
class User extends AppModel {

    /**
     * Model name
     *
     * @var string
     * @access public
     */
    var $name = 'User';   
    
    private $userinfo = null;

    /**
     * Validation
     *
     * @var array
     * @access public   
     ***/  
    // 第三方登录的，如qq，新浪微博，微信等没有用户名及邮箱，故用户名与邮箱自动生成，不允许空。
    // 邮箱允许空，有值时不允许出现重复。（注册时验证）
    var $validate = array(
        'password' => array(
            'minLength' => array(
                'rule' => array('minLength', 6),
                'message' => 'This field length must big than 6',
            ),
        ),
    );
    
    /*var $actsAs = array(
    		'Acl' => array('type' => 'requester'),
    );*/
    
    var $hasAndBelongsToMany = array(
    		'Role' => array(
				'className'              => 'Role',
				'joinTable'              => 'user_roles',
				'foreignKey'             => 'user_id', // 对应本模块的id
				'associationForeignKey'  => 'role_id', // 对应tag的id
				// 'conditions'             => array('UserRole.started >' => ''), 条件在__construct方法中设置
				'unique'                 => 'keepExisting',
				// 'limit'        => 100,
				'dependent'            => false,
				'exclusive'            => false,
				'fields' => array('Role.id','Role.name','Role.alias'),
    		    'order' => 'Role.updated desc',
    		),
        'Company' => array(
            'className'              => 'Company',
            'joinTable'              => 'company_members',
            'foreignKey'             => 'user_id', // 对应本模块的id
            'associationForeignKey'  => 'company_id', // 对应tag的id
            'unique'                 => 'keepExisting',
            'dependent'            => false,
            'exclusive'            => false,
            'fields' => array('id','name','groupid'),
            'order' => 'Company.id desc',
        ),
    );
    var $hasOne = array(
    		'UserSetting' => array(
				'className'     => 'UserSetting',
				'foreignKey'    => 'id',
				'dependent'=> false
    		),
    		
    );
    var $hasMany = array(
    		'Oauthbind' => array(
				'className'     => 'Oauthbind',
				'foreignKey'    => 'user_id',
				'dependent'=> false,
    		    'fields' => array('id','user_id','source','oauth_openid','oauth_token','oauth_name','expires','refresh_token'),
    		)
    );
    
    public function getUserWxes( $user_id, $company_id = '', $limit = 1 ){
    	$wx = loadModelObject('Wx');
        $user_wxes = $wx->find('all',array(
            'conditions'=> 	array('Wx.creator' => $user_id),
            'joins' => array(array(
                'table' => 'oauthbinds',
                'alias' => 'Oauthbind',
                'type' => 'inner',
                'conditions' => array(
                    'Wx.creator=Oauthbind.user_id',
                    'Wx.oauth_appid=Oauthbind.oauth_openid',
                    'Oauthbind.source'=>'wechatComp',
                    //'Oauthbind.updated >' => time() - 7200,
                )
            )),
            'order' => 'Oauthbind.updated desc',
            'fields' => 'Wx.*,Oauthbind.*',
            'limit' => $limit,
        ));
        if( $limit == 1 && !empty($user_wxes)) {
        	return $user_wxes[0];
        }
        return $user_wxes;
    }
    
    /**
     * 按天延长会员角色期限
     * @param unknown $user_id
     * @param unknown $role_id
     * @param number $days
     * @return boolean
     */
    public function extendRoleDays($user_id,$role_id,$days=1){
    
        $UserRole = loadModelObject('UserRole');
        $roleinfo = $UserRole->find('first',array(
            'conditions' => array( 'user_id' => $user_id,'role_id' => $role_id),
        ));
        if(empty($roleinfo)) {
            $roleinfo = array(
                'user_id' => $user_id,
                'role_id' => $role_id,
                'status' => 1,
                'started' => date('Y-m-d H:i:s'),
                'ended' => date('Y-m-d',strtotime('+'.$days.' days')).' 23:59:59',
            );
            $UserRole->create();
            $UserRole->save($roleinfo);
        }
        else{
            if( $roleinfo['UserRole']['ended'] < date('Y-m-d H:i:s') ) { // 权限已过期
                $updateinfo = array(
                    //'started' => $this->escape_string(date('Y-m-d H:i:s')) ,
                    //'ended' => $this->escape_string(date('Y-m-d',strtotime('+'.$months.' months')).' 23:59:59'),
                    'started' => date('Y-m-d H:i:s') ,
                    'ended' => date('Y-m-d',strtotime('+'.$days.' days')).' 23:59:59',
                    'id' => $roleinfo['UserRole']['id'],
                );
                $UserRole->save( $updateinfo,true,array('started','ended'));
            }
            else{ // 权限未过期，续期权限的使用时间
                $updateinfo = array();
                $updateinfo['id'] = $roleinfo['UserRole']['id'];
                // 								$updateinfo['ended'] = $this->escape_string( date('Y-m-d',strtotime('+'.$months.' months',strtotime($roleinfo['UserRole']['ended']))).' 23:59:59');
                $updateinfo['ended'] = date('Y-m-d',strtotime('+'.$days.' days',strtotime($roleinfo['UserRole']['ended']))).' 23:59:59';
                $UserRole->save( $updateinfo,true,array('ended'));
            }
        }
        return true;
    }
    
    /**
     * 按月延长会员角色期限
     * @param unknown $user_id
     * @param unknown $role_id
     * @param number $months  延长月份数量
     * @return boolean
     */
    public function extendRole($user_id,$role_id,$months=1){
        
        $UserRole = loadModelObject('UserRole');
        $roleinfo = $UserRole->find('first',array(
            'conditions' => array( 'user_id' => $user_id,'role_id' => $role_id),
        ));
        if(empty($roleinfo)) {
            $roleinfo = array(
                'user_id' => $user_id,
                'role_id' => $role_id,
                'status' => 1,
                'started' => date('Y-m-d H:i:s'),
                'ended' => date('Y-m-d',strtotime('+'.$months.' months')).' 23:59:59',
            );
            $UserRole->create();
            $UserRole->save($roleinfo);
        }
        else{
            if( $roleinfo['UserRole']['ended'] < date('Y-m-d H:i:s') ) { // 权限已过期
                $updateinfo = array(
                    //'started' => $this->escape_string(date('Y-m-d H:i:s')) ,
                    //'ended' => $this->escape_string(date('Y-m-d',strtotime('+'.$months.' months')).' 23:59:59'),
                    'started' => date('Y-m-d H:i:s') ,
                    'ended' => date('Y-m-d',strtotime('+'.$months.' months')).' 23:59:59',
                    'id' => $roleinfo['UserRole']['id'],
                );
                $UserRole->save( $updateinfo,true,array('started','ended'));
            }
            else{ // 权限未过期，续期权限的使用时间
                $updateinfo = array();
                $updateinfo['id'] = $roleinfo['UserRole']['id'];
                // 								$updateinfo['ended'] = $this->escape_string( date('Y-m-d',strtotime('+'.$months.' months',strtotime($roleinfo['UserRole']['ended']))).' 23:59:59');
                $updateinfo['ended'] = date('Y-m-d',strtotime('+'.$months.' months',strtotime($roleinfo['UserRole']['ended']))).' 23:59:59';
                $UserRole->save( $updateinfo,true,array('ended'));
            }
        }
        return true;
    }
    
    public function getUserByEmail($email) {
        $data = $this->find('first', array(
            'conditions' => array('User.email' => $email),
            'recursive' => 1,
        ));
        if(empty($data['User'])) {
        	return array();
        }
        
        if( !is_array($data['User']['role_id']) ) {
            $data['User']['role_id'] = array_filter(explode(',',$data['User']['role_id']));
        }
         
        if( !empty($data['Role']) ) {
            foreach($data['Role'] as $k => $role) {
                $data['Role'][$k]['started'] = $role['UserRole']['started'];
                $data['Role'][$k]['ended'] = $role['UserRole']['ended'];
                unset($data['Role'][$k]['UserRole']);
                if( !in_array($role['id'],$data['User']['role_id']) ){
                    $data['User']['role_id'][] = $role['id'];
                }
            }
        }
        if( !empty($data['Company']) ) {
            foreach($data['Company'] as $k => $com) {
                if( $com['id'] == 1) {
                    unset($data['Company'][$k]); //去掉编号1的公司不在前台显示
                    continue;
                }
                $data['Company'][$k]['role_id'] = $com['CompanyMember']['role_id'];
                unset($data['Company'][$k]['CompanyMember']);
            }
        }

        if( ! in_array(2,$data['User']['role_id']) ) {
            $data['User']['role_id'][] = 2;
        }
        $data['User']['role_id'] = array_unique($data['User']['role_id']);
        if( !empty($data['UserSetting']) ) {
        	$data['UserSetting'] = json_decode($data['UserSetting']['settings'],true);
        }
        $data['User']['Role'] =  $data['Role'];
        $data['User']['Oauthbind'] = $data['Oauthbind'];
        $data['User']['UserSetting'] =  $data['UserSetting'];
        //unset($data['Role']);unset($data['Oauthbind']);
        return $data;
    }
    
    public function getUserByMobile($mobile) {
        $data = $this->find('first', array(
            'conditions' => array('User.mobile' => $mobile),
            'recursive' => 1,
        ));
        if(empty($data['User'])) {
            return array();
        }
    
        if( !is_array($data['User']['role_id']) ) {
            $data['User']['role_id'] = array_filter(explode(',',$data['User']['role_id']));
        }
        
        if( !empty($data['Role']) ) {
            foreach($data['Role'] as $k=>$role) {
                $data['Role'][$k]['started'] = $role['UserRole']['started'];
                $data['Role'][$k]['ended'] = $role['UserRole']['ended'];
                unset($data['Role'][$k]['UserRole']);
                if( !in_array($role['id'],$data['User']['role_id']) ){
                    $data['User']['role_id'][] = $role['id'];
                }
            }
        }
        if( !empty($data['Company']) ) {
            foreach($data['Company'] as $k => $com) {
                if( $com['id'] == 1) {
                    unset($data['Company'][$k]); //去掉编号1的公司不在前台显示
                    continue;
                }
                $data['Company'][$k]['role_id'] = $com['CompanyMember']['role_id'];
                unset($data['Company'][$k]['CompanyMember']);
            }
        }

        if( ! in_array(2,$data['User']['role_id']) ) {
            $data['User']['role_id'][] = 2;
        }
        $data['User']['role_id'] = array_unique($data['User']['role_id']);
        if( !empty($data['UserSetting']) ) {
            $data['UserSetting'] = json_decode($data['UserSetting']['settings'],true);
        }
        $data['User']['Role'] =  $data['Role'];
        $data['User']['Oauthbind'] = $data['Oauthbind'];
        $data['User']['UserSetting'] =  $data['UserSetting'];
        //unset($data['Role']);unset($data['Oauthbind']);
        return $data;
    }

    
    public function getUserById($user_id){
        
        if( !empty($this->userinfo) && $this->userinfo['User']['id'] == $user_id ) {
            return $this->userinfo;
        }
        
        $data = $this->find('first', array(
            'conditions' => array('User.id' => $user_id),
            'recursive' => 1,
        ));
        
        if( empty($data['User']) ) {
        	return array();
        }
        if( !is_array($data['User']['role_id']) ) {
            $data['User']['role_id'] = array_filter(explode(',',$data['User']['role_id']));
        }
         
        if( !empty($data['Role']) ) {
            foreach($data['Role'] as $k => $role) {
                $data['Role'][$k]['started'] = $role['UserRole']['started'];
                $data['Role'][$k]['ended'] = $role['UserRole']['ended'];
                unset($data['Role'][$k]['UserRole']);
                if( !in_array($role['id'],$data['User']['role_id']) ){
                    $data['User']['role_id'][] = $role['id'];
                }
            }
        }
        if( !empty($data['Company']) ) {
            foreach($data['Company'] as $k => $com) {
                if( $com['id'] == 1) {
                    unset($data['Company'][$k]); //去掉编号1的公司不在前台显示
                    continue;
                }
                $data['Company'][$k]['role_id'] = $com['CompanyMember']['role_id'];
                unset($data['Company'][$k]['CompanyMember']);
            }
        }

        $data['User']['role_id'] = array_unique($data['User']['role_id']);
        if( !empty($data['UserSetting']) ) {
        	$data['UserSetting'] = json_decode($data['UserSetting']['settings'],true);
        }
        
        if( ! in_array(2,$data['User']['role_id']) ) {
            $data['User']['role_id'][] = 2;
        }
        
        $data['User']['Role'] =  $data['Role'];
        $data['User']['Oauthbind'] = $data['Oauthbind'];
        $data['User']['UserSetting'] =  $data['UserSetting'];
        //unset($data['Role']);unset($data['Oauthbind']);
        
        $this->userinfo =  $data;
        return $data;
    }

    public function getUserInfo($user_id){
        return $this->getUserById($user_id);
    }
    
    public function isPaidUser($user_id) {
        if( empty($this->userinfo) || $this->userinfo['User']['id'] != $user_id ) {
            $this->userinfo = $this->getUserInfo($user_id);
        }
        
        if( count($this->userinfo['User']['role_id']) > 1 ) { //付费会员用户组数大于1
            return true;
        }
        else{
            return false;
        }
    }
    
    public function getOauthOpenId($user,$source) {

        if(!is_array($source)){
            $source = array($source);
        }
        
        if( is_array($user['Oauthbind']) ) {
            foreach($user['Oauthbind'] as $oauth){
                if(in_array($oauth['source'], $source)) {
                    return $oauth['oauth_openid'];
                }
            }
        }
        else{
            $oauthObj = loadModelObject('Oauthbind');
            $uid = $user['id'];
            $result = $oauthObj->find('first',array(
                'conditions' => array( 'user_id'=>$uid,'source'=> $source ),
                'recursive' => -1,
            ));
            if( !empty($result) ) {
                return $result['Oauthbind']['oauth_openid'];
            }
        }
    	return null;
    }
    
    public function __construct($id=false,$table=null,$ds=null) {
    	parent::__construct($id,$table,$ds);
    	/* 设置用户权限的开始结束时间条件，获取有效的用户权限，过期的都去除  */
    	$this->hasAndBelongsToMany['Role']['conditions'] = array(
    			'UserRole.started <' => date('Y-m-d H:i:s'),
    			'UserRole.ended >' => date('Y-m-d H:i:s'),
    	);
    	
    }

    public function getUserSimple($user_id) {
        $cache_key = 'simu_'.$user_id;
        $user = Cache::read($cache_key);
        if( empty($data) ){
            $data = $this->find('first',array(
                'conditions'=>array( 'id' => $user_id,),
                'fields' => '*',
                'recursive' => -1,
            ));
            $user = $data['User'];
            Cache::write($cache_key,$user);
        }


        return $user;
    }
    
    public function getUserScore($user_id) {
    	$data = $this->find('first',array(
    		'conditions'=>array( 'id' => $user_id,),
    		'fields' => 'score',
    		'recursive' => -1,
    	));
    	return $data['User']['score'];
    }
    
    
    function getNewUCUserId($username,$passwd,$email,$ip) {
    	if(defined('UC_APPID')){
    		App::import('Vendor', '',array('file' => 'uc_client'.DS.'client.php'));
    		if(UC_DBCHARSET =='gbk'){
    			App::uses('Charset', 'Lib');
    			$username = Charset::utf8_gbk($username);
    		}
    		
    		$i = 0;
    		do{
    			$uid = uc_user_register($username,$passwd,$email,'','', $ip);
    			if($uid<=0){
    				if($uid == -1) {
    					$error_msg = '用户名不合法';
    				} elseif($uid == -2) {
    					$error_msg = '包含不允许注册的词语';
    				} elseif($uid == -3) {
    					$error_msg = '用户名已经存在';
    				} elseif($uid == -4) {
    					$error_msg = 'Email 格式有误';
    				} elseif($uid == -5) {
    					$error_msg = 'Email 不允许注册';
    				} elseif($uid == -6) {
    					$error_msg = '该 Email 已经被注册';
    				} else{
    					$error_msg = '未知错误';
    				}
    			}
    			else{
    				return $uid;
    			}
    			$i++;
    		}while($uid < 0 && $i < 5);
    		echo $error_msg;exit;
    	}
    	return null;
    }
    
}
?>